package com.example.cachecontroldemo.interceptor;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;

@Slf4j
public abstract class AbstractCacheControlValidator {

    protected String getPathVarId(HttpServletRequest request) {
        int lastIndexOf = request.getRequestURI().lastIndexOf("/");
        return request.getRequestURI().substring(lastIndexOf + 1);
    }

    /**
     * 执行缓存有效性验证的核心方法
     * @param request
     * @param response
     * @return
     * @throws SQLException
     */
    public boolean validate(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        String ifModifiedSince = request.getHeader("If-Modified-Since");
        Long lastModified = getLastModified(request);

        // 约定：如果返回Long.MIN_VALUE表示未获取到最后更新时间，则缓存验证不通过
        if (StrUtil.isNotBlank(ifModifiedSince)
                && Long.MIN_VALUE != lastModified
                && BooleanUtil.isTrue(lastModified <= Long.parseLong(ifModifiedSince))) {
            return true;
        }
        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Last-Modified", String.valueOf(lastModified));
        return false;
    }

    /**
     * 获取资源的最后更新时间，由每个实现类自己实现
     * @param request
     * @return
     * @throws SQLException
     */
    protected abstract Long getLastModified(HttpServletRequest request) throws SQLException;
}
